import java.util.ArrayList;
import java.util.List;

public class Solution131 {
    //boolean[][] f;
    int[][] f;
    List<List<String>> res;
    List<String> ans;
    int n;

    public List<List<String>> partition(String s) {
        res = new ArrayList<>();
        n = s.length();
        //f = new boolean[n][n];
        f = new int[n][n];
        ans = new ArrayList<>();
        /*
        for (int i = 0; i < n; i++) {
            Arrays.fill(f[i], true);
        }
        for (int i = n - 1; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                f[i][j] = (s.charAt(i) == s.charAt(j)) && f[i + 1][j - 1];
            }
        }
        */

        dfs(s, 0);
        return res;
    }

    private void dfs(String s, int start) {
        if (start == n) {
            res.add(new ArrayList<>(ans));
            return;
        }
        /*
        for (int i = start; i < n; i++) {
            if (f[start][i]) {
                ans.add(s.substring(start, i + 1));
                dfs(s, i + 1);
                ans.remove(ans.size() - 1);
            }
        }
        */
        for (int i = start; i < n; i++) {
            if (isPalindrome(s, start, i) == 1) {
                ans.add(s.substring(start, i + 1));
                dfs(s, i + 1);
                ans.remove(ans.size() - 1);
            }
        }
    }

    private int isPalindrome(String s, int i, int j) {
        if (f[i][j] != 0) {
            return f[i][j];
        }
        if (i >= j) {
            f[i][j] = 1;
        } else if (s.charAt(i) == s.charAt(j)) {
            f[i][j] = isPalindrome(s, i + 1, j - 1);
        } else {
            f[i][j] = -1;
        }
        return f[i][j];
    }
}
